import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import moment from 'moment'
import {
  setDisable,
  getnetworkList,
  setDelete,
  getNetworkExportFields,
  getNetworkSysInitExportField,
  getNetworkCustomField,
  saveAndExportNetworkField,
  saveExportNetworkField,
} from '../../../api/network'

  // 使用获取服务商分类下拉选项服务

export default function () {
  const loading = ref(false)
  const name = ref('')
  const addrsDom = ref()
  const total = ref(0)
  const tableDataList = ref(null)
  const type = ref(null)
  const pagination = ref()
  const category = ref(null)
  const exportFields = ref<{ name: string; type: number; value: string; showClose?: boolean }[]>([])
  const sysInitExportFields = ref<{ code: string; id: string; name: string; showAdd?: boolean }[]>(
    [],
  )
  const __sysInitExportFields = ref<{ code: string; id: string; name: string }[]>([])
  const customFields = ref<{ id: string; code: null; name: string; showAdd?: boolean }[]>([])
  const __customFields = ref<{ id: string; code: null; name: string }[]>([])
const teamType=ref(null)//团队模式

  // 获取服务商列表
  const getnetworkListRows = () => {
    loading.value = true
    const data = {
      category: category.value, //服务商模式：1-内部服务商，2-外部服务商，3-第三方服务商
      type: type.value, //网点服务类型：1-销售网点，2-售后网点
      networkTypeId: networkTypeId.value, //网点分类ID
      networkSearch: name.value, //服务商名称
      page: pagination.value.current, //当面页码
      limit: pagination.value.size, //每页显示数量
      teamType:teamType.value
    }
    getnetworkList(data).then((res) => {
      if (res.data.code == 20000) {
        tableDataList.value = res.data.data.rows
        total.value = Number(res.data.data.total)
      } else {
        if (res.data.isError)
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'error',
            duration: 4000,
            offset: 200,
          })
      }
      loading.value = false
    })
  }

  // 获取所有服务商导出字段
  const getNetworkExportFieldList = async () => {
    loading.value = true
    const res = await getNetworkExportFields()
    if (res.data.code == 20000) {
      exportFields.value = res.data.data.rows.map((column) => {
        column.showClose = false
        return column
      })
    } else {
      if (res.data.isError)
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: 'error',
          duration: 4000,
          offset: 200,
        })
    }
    loading.value = false
  }

  // 获取服务商初始化系统导出字段
  const getNetworkSysInitExportFieldList = async () => {
    loading.value = true
    const res = await getNetworkSysInitExportField()
    if (res.data.code == 20000) {
      sysInitExportFields.value = res.data.data.rows.map((column) => {
        column.showAdd = false
        return column
      })
      __sysInitExportFields.value = [...res.data.data.rows]
    } else {
      if (res.data.isError)
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: 'error',
          duration: 4000,
          offset: 200,
        })
    }
    loading.value = false
  }

  // 获取服务商自定义字段
  const getNetworkCustomFieldList = async () => {
    loading.value = true
    const res = await getNetworkCustomField()
    if (res.data.code == 20000) {
      customFields.value = res.data.data.rows.map((column) => {
        column.showAdd = false
        return column
      })
      __customFields.value = [...res.data.data.rows]
    } else {
      if (res.data.isError)
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: 'error',
          duration: 4000,
          offset: 200,
        })
    }
    loading.value = false
  }

  // 移除全部导出字段
  const handleRemoveAllExportField = () => {
    exportFields.value.forEach((column) => {
      if (column.type === 1) {
        const __column = __sysInitExportFields.value.find((item) => item.name === column.name)
        sysInitExportFields.value.push(__column)
      } else if (column.type === 2) {
        const __column = __customFields.value.find((item) => item.name === column.name)
        customFields.value.push(__column)
      }
    })
    exportFields.value = []
  }

  // 添加全部字段
  const handleAddALLToExportFields = (type: number) => {
    if (type === 1) {
      sysInitExportFields.value.forEach((column) => {
        exportFields.value.push({
          name: column.name,
          type,
          value: column.code,
          showClose: false,
        })
      })
      sysInitExportFields.value = []
    } else if (type === 2) {
      customFields.value.forEach((column) => {
        exportFields.value.push({
          name: column.name,
          type,
          value: column.id,
          showClose: false,
        })
      })
      customFields.value = []
    }
  }

  const ids = ref([])
  async function changeAll(n: number, str: string) {
    if (ids.value.length == 0) {
      ElMessage({
        message: `请选择要${str}的服务商`,
        type: 'warning',
        duration: 2000,
        offset: 200,
      })
      return
    }
    ElMessageBox({
      //
      title: '提示',
      message: `确认${str}的该服务商?`,
      showCancelButton: true,
      closeOnClickModal: false,
      type: n === 3 ? 'error' : 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
    })
      .then(async () => {
        loading.value = true
        switch (n) {
          case 1:
          case 2:
            await setDisable(ids.value, n == 1 ? false : true).then((res) => {
              if (res.data.isError)
                ElMessage({
                  showClose: true,
                  message: res.data.message,
                  type: res.data.success ? 'success' : 'error',
                  offset: 200,
                })
              if (res.data.success) {
                ids.value = []
                getnetworkListRows()
              }
              loading.value = false
            })
            break
          case 3:
            await setDelete(ids.value).then((res) => {
              if (res.data.isError)
                ElMessage({
                  showClose: true,
                  message: res.data.message,
                  type: res.data.success ? 'success' : 'error',
                  offset: 200,
                })
              if (res.data.success) {
                ids.value = []
                getnetworkListRows()
              }
              loading.value = false
            })
            break
        }
      })
      .catch()
  }
  function handleChange(val) {
    ids.value = []
    val.filter((o) => {
      ids.value.push(o.id)
    })
  }
const networkTypeId2=ref('')
  // 保存并导出服务商字段
  function handleSaveAndExportNetworkField() {
    if (exportFields.value.length === 0) {
      ElMessage({
        showClose: true,
        message: '至少选择一个导出字段',
        type: 'error',
        offset: 200,
      })
      return false
    }

    const data = {
      category: category.value, //服务商模式：1-内部服务商，2-外部服务商，3-第三方服务商
      type: type.value, //网点服务类型：1-销售网点，2-售后网点
      networkTypeId: networkTypeId2.value, //网点分类ID
      networkSearch: name.value, //服务商名称
      page: 1, //当面页码
      limit: 50, //每页显示数量
    }

    exportFields.value.forEach((column) => {
      delete column.showClose
    })

    saveAndExportNetworkField({
      exportFieldVo: {
        fieldAttrs: exportFields.value,
      },
      networkSelectVo: data,
    }).then((res) => {
      // 因为前端把responseType: 'blob'放到请求头里，所以当后端响应JSON时也会把JSON转为blob
      // 所以需要将响应的数据转回JSON对象，如果转换成功就说明返回的是JSON，否则则是文件流
      const reader = new FileReader()
      reader.readAsText(res.data)
      reader.onload = function (result) {
        try {
          // 解析对象成功，说明后端返回的是JSON
          const resData = JSON.parse(result.target.result as string)
          ElMessage({
            showClose: true,
            message: resData.message,
            type: 'warning',
            offset: 200,
          })
        } catch (err) {
          // 解析失败，说明后端返回的是文件流
          ElMessage({
            showClose: true,
            message: '服务商数据导出成功',
            type: 'success',
            offset: 200,
          })
          const url = window.URL.createObjectURL(new Blob([res.data], { type: '.xlsx' }))
          const link = document.createElement('a')
          link.href = url
          link.download = `服务商_${moment(new Date()).format('YYYYMMDD')}.xlsx`
          link.click()
        }
      }
    })
  }

  // 保存服务商导出字段
  function handleSaveNetworkField() {
    if (exportFields.value.length === 0) {
      ElMessage({
        showClose: true,
        message: '至少选择一个导出字段',
        type: 'error',
        offset: 200,
      })
      return false
    }

    exportFields.value.forEach((column) => {
      delete column.showClose
    })

    saveExportNetworkField({
      fieldAttrs: exportFields.value,
    }).then((res) => {
      if (res.data.isError)
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: res.data.success ? 'success' : 'error',
          offset: 200,
        })
    })
  }

  // 系统字段添加
  const handleAddToExportFields = (
    column: { code: any; id: string; name: string },
    type: number,
  ) => {
    exportFields.value.push({
      name: column.name,
      type,
      value: type === 1 ? column.code : column.id,
      showClose: false,
    })
    if (type === 1) {
      const index = sysInitExportFields.value.findIndex((item) => item.id === column.id)
      sysInitExportFields.value.splice(index, 1)
    } else if (type === 2) {
      const index = customFields.value.findIndex((item) => item.id === column.id)
      customFields.value.splice(index, 1)
    }
  }

  // 从导出字段中移除
  const handleRemoveFromExportFields = (column: { name: string; type: number; value: string }) => {
    const index = exportFields.value.findIndex((item) => item.name === column.name)
    exportFields.value.splice(index, 1)
    if (column.type === 1) {
      const __column = __sysInitExportFields.value.find((item) => item.name === column.name)
      sysInitExportFields.value.push({ ...__column, showAdd: false })
    } else if (column.type === 2) {
      const __column = __customFields.value.find((item) => item.name === column.name)
      customFields.value.push({ ...__column, showAdd: false })
    }
  }
const networkTypeId=ref(null)
  function valueChange() {
    getnetworkListRows()
  }
  onMounted(() => {
    getnetworkListRows()
  })

  return {
    handleChange,
    handleSaveAndExportNetworkField,
    handleAddToExportFields,
    handleRemoveFromExportFields,
    handleRemoveAllExportField,
    handleSaveNetworkField,
    handleAddALLToExportFields,
    valueChange,
    changeAll,
    ids,
    addrsDom,
    loading,
    getnetworkListRows,
    getNetworkExportFieldList,
    getNetworkSysInitExportFieldList,
    getNetworkCustomFieldList,
    total,
    category,
    type,
    pagination,
    tableDataList,
    networkTypeId,
    networkTypeId2,
    name,
    exportFields,
    sysInitExportFields,
    customFields,
    teamType
  }
}
